package com.example.framework2002a.view.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

public class FlowLayout extends ViewGroup {

    private boolean flag = false;
    private boolean layoutFlag = false;

    public FlowLayout(Context context) {
        super(context);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    //测量
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (flag){
            return;
        }
        flag = true;

        measureChildren(widthMeasureSpec,heightMeasureSpec);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        currentViewGroupWidth = this.getMeasuredWidth();
    }

    //前一次xy坐标位置
    int x = 0;
    int y = 0;

    //当前ViewGroup的宽高
    int currentViewGroupWidth = 0;

    //布局摆放 确认 左上右下
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (layoutFlag){
            return;
        }
        layoutFlag = true;

        int subViewCount = getChildCount();

        for (int i = 0; i < subViewCount; i++) {
            View childAt = getChildAt(i);

            //当前子View的宽高
            int subViewWidth = childAt.getMeasuredWidth();
            int subViewHeight = childAt.getMeasuredHeight();

            if ((x+subViewWidth) > currentViewGroupWidth){
                x = 0;
                y = y + subViewHeight;
            }

            childAt.layout(x+5,y+5,x+subViewWidth,y+subViewHeight);
            x += subViewWidth;
        }
    }
}
